package sort;

import java.util.Arrays;
import java.util.Random;
import java.util.stream.Collectors;

public class QuickSort {

    public static void quickSort(int[] arr) {
        if(arr == null || arr.length <= 1){
            return;
        }
        int n = arr.length;
        quickSort(arr, 0, n-1);
    }

    public static void quickSort(int[] arr, int left, int right){
        if(left < right){
            int randomIndex = new Random().nextInt(right - left) + left;
            swap(arr, left, randomIndex);
            int index = partition(arr, left, right);
            quickSort(arr, left, index-1);
            quickSort(arr, index + 1, right);
        }
    }

    public static int partition(int[] arr, int left, int right){
        int pivot = arr[left];
        while (left < right){
            while (left < right && arr[right] >= pivot){
                right--;
            }
            arr[left] = arr[right];
            while (left < right && arr[left] <= pivot){
                left++;
            }
            arr[right] = arr[left];
        }
        arr[left] = pivot;
        return left;
    }

    public static void swap(int[] arr, int i, int j){
        if( i == j){
            return;
        }
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
        return;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{61, 17, 29, 22, 34, 60, 72, 21, 50, 1, 62};
        quickSort(arr);
        System.out.println(Arrays.stream(arr).boxed().collect(Collectors.toList()));
    }
}
